﻿using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sustainalytics.OS;

namespace Sustainalytics.Os.Utils.Tests
{
    [TestClass]
    public class LinkedLauncherTests
    {
        [TestMethod]
        public void WhenTheLinkedProcessIsDisposed_The_SpawnedProcessIsKilled()
        {
            string cmd = "cmd";

            Process process = null;
            using (var linkedProcess = LinkedProcess.Start(cmd, false, true))
            {
                process = Process.GetProcessById((int)linkedProcess.ProcessId);
            }

            Assert.IsTrue(process != null, "Process must be not null");
            Assert.IsTrue(process.HasExited, "the process must exist on linkedProcess dispose");
        }


        [TestMethod]
        public void WhenTheParentProcessIsKilled_The_ChildProcessIsKilled()
        {
            string cmd = "cmd";
            Process parent = Process.Start("Sustainalytics.ESGComputing.Launcher.exe", "\"Sustainalytics.Dummy.Console.exe\"");

            Thread.Sleep(500); //wait for the child process to start
            Process[] children = Process.GetProcessesByName("Sustainalytics.Dummy.Console");

            Assert.IsTrue(parent.HasExited != true);
            Assert.IsTrue(children != null);
            Assert.IsTrue(children.Length == 1);
            
            parent.Kill();
            Thread.Sleep(500); //wait for the child to die
            Assert.IsTrue(children[0].HasExited);
        }



        [TestMethod]
        [ExpectedException(typeof(ProcessLaunchException))]
        public void WhenStartedWithUnknownCommand_ProcessLaunchException_IsThrown()
        {
            string cmd = "cmd"+Guid.NewGuid();

            Process process = null;
            using (var linkedProcess = LinkedProcess.Start(cmd, false, false))
            {
                process = Process.GetProcessById((int)linkedProcess.ProcessId);
            }
           
        }

    }
}
